package com.example.zjx8969.myapplication.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatTextView;

/**
 * Created by wjj3771 on 2016/5/31.
 */
public class CenterTextView extends AppCompatTextView {

    public CenterTextView(Context context) {
        super(context);
    }

    public CenterTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CenterTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        setCanvasCoord(canvas);
        super.onDraw(canvas);
    }

    private void setCanvasCoord(Canvas canvas) {

        Drawable[] drawables = getCompoundDrawables();
        //just for DrawableLeft and DrawableRight
        if (drawables != null) {
            int drawablePadding = getCompoundDrawablePadding();
            int drawableLeftW = 0;
            if (drawables[0] != null) {
                drawableLeftW = drawables[0].getIntrinsicWidth();
            }
            int drawableRightW = 0;

            if (drawables[2] != null) {
                drawableRightW = drawables[2].getIntrinsicWidth();
            }

            float contentWidth = 0;

            if (drawableLeftW > 0) {
                contentWidth = contentWidth + drawableLeftW + drawablePadding;
            }

            if (drawableRightW > 0) {
                contentWidth = contentWidth + drawableRightW + drawablePadding;
            }

            if (contentWidth > 0) {
                float textWidth = getPaint().measureText(getText().toString());
                contentWidth = contentWidth + textWidth;
                canvas.translate((getWidth() - contentWidth - getPaddingRight() - getPaddingLeft()) / 2, 0);
            }
        }
    }

}
